/*
 * Copyright 2004-2005 asoft
 * 本软件及其所有拷贝的名称，与光盘上或本软件中注明的公司同在。
 * 本软件及文档享有版权，并受国家版权法及国际协约条款的保护。
 * 您不可以从本软件中去掉其版权声明；并保证为本软件的拷贝（本部或部分）* 复制版权声明。
 * 您同意制止以任何形式非法拷贝本软件及文档。
 * 版权信息参见：
 *      http://www.asoft.cn/licenses
 */

package com.asoft.examonline.exammanager.valid;

import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.asoft.common.basedata.manager.TypeManager;
import com.asoft.common.basedata.model.Type;
import com.asoft.common.runningtime.Time;
import com.asoft.common.util.mvc.valid.UserValidator;
import com.asoft.common.util.mvc.valid.ValidatedResult;
import com.asoft.examonline.exammanager.define.SelectedQuestion;
import com.asoft.examonline.exammanager.manager.ExamQuestionManager;
import com.asoft.examonline.exammanager.model.ExamQuestion;
import com.asoft.examonline.exammanager.model.Result;

/**
 * <p>Title: 试题校验模板</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: asoft</p>
 * @ $Author: author $
 * @ $Date: 2005/02/16 01:04:14 $
 * @ $Revision: 1.7 $
 * @ created in 2005-11-14
 *
 */

public  class ExamQuestionsValidatorTemplet extends UserValidator
{
        static Logger logger = Logger.getLogger(ExamQuestionsValidatorTemplet.class);
        
        protected Time time;
        
        protected ExamQuestionManager examQuestionManager;
        
        protected TypeManager typeManager;

        /**
         * @param examQuestionManager 要设置的 examQuestionManager
         */
        public void setExamQuestionManager(ExamQuestionManager examQuestionManager)
        {
                this.examQuestionManager = examQuestionManager;
        }
        
        /**
         * @param typeManager 要设置的 typeManager
         */
        public void setTypeManager(TypeManager typeManager)
        {
                this.typeManager = typeManager;
        }

        public void setTime(Time time)
        {
                this.time = time;
        }
        
        // 所有类型、题目内容校验
        public void validingTypesAndContent(HttpServletRequest request,ValidatedResult vr)
        {
                Type difficulty = (Type)this.validBaseObjectById(request, vr, this.typeManager, "difficultyId");
                if(difficulty == null)
                {
                        vr.setErrMess("difficultyId", "请选择");
                }
                
                Type questType = (Type)this.validBaseObjectById(request, vr, this.typeManager, "questTypeId");
                if(questType == null)
                {
                        vr.setErrMess("questTypeId", "请选择");
                }
                
                Type source = (Type)this.validBaseObjectById(request, vr, this.typeManager, "sourceId");
                if(source == null)
                {
                        vr.setErrMess("sourceId", "请选择");
                }
                
                Type knowledgePoint = (Type)this.validBaseObjectById(request, vr, this.typeManager, "knowledgePointId");
                if(knowledgePoint == null)
                {
                        vr.setErrMess("knowledgePointId", "请选择");
                }
                
                Type knowledgeType = (Type)this.validBaseObjectById(request, vr, this.typeManager, "knowledgeTypeId");
                if(knowledgeType == null)
                {
                        vr.setErrMess("knowledgeTypeId", "请选择");
                }
                
                String content = this.validString(request, vr, "content", 1, 20000);
                String resolution = this.validString(request, vr, "resolution", 1, 20000);
                String authorName = this.validString(request, vr, "authorName", 1, 50); 
                
                if(vr.isAllValidated())
                {
                        request.setAttribute("difficultyId", difficulty);
                        request.setAttribute("questTypeId", questType);
                        request.setAttribute("sourceId", source);
                        request.setAttribute("knowledgePointId", knowledgePoint);
                        request.setAttribute("knowledgeTypeId", knowledgeType);
                }
        }

        /**
         * 批量删除前的校验
         *
         * @ param: HttpServletRequest request
         * @ param: ValidatedResult vr 校验结果存放器
         * @ param: String[] params 配置参数
         */
        public void validing(HttpServletRequest request,ValidatedResult vr,String[] params)
        {
                throw new UnsupportedOperationException("不支持该操作");
        }
        
        // 生成试题编号（规则： 知识点编号+ 当前时间+ 随机数）
        public String makingCode(Type knowledegePoint)
        {
                String newCode = null;
                int i = 0;
                do
                {
                        newCode = knowledegePoint.getCode() + (this.time.now().getTime() + i);
                        i++;
                }while(this.typeManager.getByCode(newCode) != null);
                return newCode;
        }
        
        // 构造答案4选择题
        public Set makingResults(HttpServletRequest request)
        {
                Set results = new LinkedHashSet();
                String[] resultStrs = request.getParameterValues("result");
                int resultCount = this.validInt(request, null, "resultCount", true);
                logger.debug("答案个数： " + resultCount);
                logger.debug("答案内容个数：" + resultStrs.length);
                for(int i = 0; i < resultCount; i ++)
                {
                        String resultContent = request.getParameter("resultContent" + i);
                        if(resultContent == null)
                        {
                            continue;    
                        }
                        logger.debug(i + ". content : " + resultContent);
                        Result result = new Result();
                        result.setCode(Integer.toString(i));
                        result.setContent(resultContent);
                        result.setPri(Integer.toString(i));
                        result.setRight(false);
                        results.add(result);
                }
                if(resultStrs != null)
                {
                        for(int i =0; i < resultStrs.length; i ++)
                        {
                                int index = Integer.parseInt(resultStrs[i]);
                                logger.debug("index: " + index);
                                if(index < resultCount)
                                {
                                        ((Result)(results.toArray())[index]).setRight(true);
                                }
                        }
                }
                return results;
        }
        
        public void putExamQuestion2Results(ExamQuestion examQuestion,Set results)
        {
                Object[] rs = results.toArray();
                for(int i =0; i < rs.length; i ++)
                {
                        Result r = (Result)rs[i];
                        r.setExamQuestion(examQuestion);
                }
        }        
        
        private Set<Type> parseKnownledgePoints(HttpServletRequest request)
        {
                Set<Type> pks = new java.util.LinkedHashSet<Type>();
                for(String pkId : request.getParameterValues("knowledgePointId"))
                {
                        pks.add((Type)this.typeManager.get(pkId));
                }
                return pks;                
        }
        
        public void validing4Add(HttpServletRequest request)
        {
                ExamQuestion eq = new ExamQuestion();
                eq.setKnowledgePoints(this.parseKnownledgePoints(request));
                eq.setQuestType((Type)this.validBaseObjectById(request, null, this.typeManager, "questTypeId"));                
                eq.setDifficulty((Type)this.validBaseObjectById(request, null, this.typeManager, "difficultyId"));
                eq.setSource((Type)this.validBaseObjectById(request, null, this.typeManager, "sourceId"));
                eq.setAuthorName(request.getParameter("authorName"));
                eq.setContent(request.getParameter("content"));
                eq.setResolution(request.getParameter("resolution"));
                eq.setResults(this.makingResults(request));
                Type kp = (Type)eq.getKnowledgePoints().toArray()[0];
                eq.setCode(this.makingCode(kp));
                request.setAttribute(ExamQuestion.class.getName(), eq);
        }
        
        public void validing4Update(HttpServletRequest request)
        {
                ExamQuestion eq = (ExamQuestion)this.examQuestionManager.get(request.getParameter("id"));
                eq.setKnowledgePoints(this.parseKnownledgePoints(request));
                eq.setDifficulty((Type)this.validBaseObjectById(request, null, this.typeManager, "difficultyId"));
                eq.setSource((Type)this.validBaseObjectById(request, null, this.typeManager, "sourceId"));
                eq.setAuthorName(request.getParameter("authorName"));
                eq.setContent(request.getParameter("content"));
                eq.setResolution(request.getParameter("resolution"));
                eq.setResults(this.makingResults(request));
                Type kp = (Type)eq.getKnowledgePoints().toArray()[0];
                request.setAttribute(ExamQuestion.class.getName(), eq);
        }
}
